//
//  GalleryView.m
//  WanCaiC8
//
//  Created by tangang on 2018/4/21.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "GalleryView.h"
#import "LabCell.h"
#import "StickyHeaderLayout.h"
#import "DSCollectionView.h"
#import "GalleryHeadView.h"

#import "AdvertisingNoImageCell.h"
#import "AdvertisingBigImageCell.h"
#import "AdvertisingMoreImageCell.h"
#import "AdvertisingSmallImageCell.h"
#import "ImageCell.h"
#import "GalleryDetailVC.h"
@interface GalleryView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,DSCollectionViewDelegate>
@property (nonatomic ,strong) DSCollectionView *collectionView;
@property (nonatomic ,strong) NSMutableArray   *dataArr;
@end

@implementation GalleryView{
    NSMutableArray     *sections;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (instancetype)init{
    if (self=[super init]) {
        [self addSubview:self.collectionView];
        [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self);
            make.top.equalTo(self).with.offset(5);
        }];
    }
    return self;
}

- (void)setModel:(GalleryModel *)model{
    _model=model;
    [self.dataArr removeAllObjects];
    sections=[[NSMutableArray alloc]init];
    for (GalleryContentModel *contentModel in model.PageData) {
        if ([sections containsObject:contentModel.QuickQuery]) {
            NSMutableArray *contentArr=self.dataArr.lastObject;
            [contentArr addObject:contentModel];
        }else{
            NSMutableArray *contentArr=[[NSMutableArray alloc]init];
            [contentArr addObject:contentModel];
            [self.dataArr addObject:contentArr];
            [sections addObject:contentModel.QuickQuery];
        }
    }
    if (sections.count>0) {
        if ([sections.firstObject isEqualToString:@"#"]) {
            [sections removeObjectAtIndex:0];
            [sections addObject:@"#"];
            [self.dataArr addObject:self.dataArr[0]];
            [self.dataArr removeObjectAtIndex:0];
        }
    }
    [self.collectionView reloadData];
}

- (void)setArr6:(NSMutableArray *)arr6{
    _arr6=arr6;
    [self.collectionView reloadData];
}

- (void)setSearchKey:(NSString *)key{
    [self.dataArr removeAllObjects];
    sections=[[NSMutableArray alloc]init];
    for (GalleryContentModel *contentModel in self.model.PageData) {
        if ([contentModel.Name containsString:key]) {
            if ([sections containsObject:contentModel.QuickQuery]) {
                NSMutableArray *contentArr=self.dataArr.lastObject;
                [contentArr addObject:contentModel];
            }else{
                NSMutableArray *contentArr=[[NSMutableArray alloc]init];
                [contentArr addObject:contentModel];
                [self.dataArr addObject:contentArr];
                [sections addObject:contentModel.QuickQuery];
            }
        }
        
    }
    [self.collectionView reloadData];
}

- (float)getViewHeight:(AdvertisingModel *)model{
    float height=0;
    if (model.ThumbStyle==0) {
        height =[TGTools getSpaceLabelHeight:model.Title withFont:[UIFont systemFontOfSize:real_size(15)] withWidth:SCREEN_WIDTH-27 andLineSpacing:5]+55;
        height-=33;
    }else if (model.ThumbStyle==1){
        height =[TGTools getSpaceLabelHeight:model.Title withFont:[UIFont systemFontOfSize:real_size(15)] withWidth:SCREEN_WIDTH-27-125 andLineSpacing:5]+55;
        
        height-=33;
        
        if (height<95) {
            height=95;
        }
        
    }else if (model.ThumbStyle==2){
        height =[TGTools getSpaceLabelHeight:model.Title withFont:[UIFont systemFontOfSize:real_size(15)] withWidth:SCREEN_WIDTH-27 andLineSpacing:5]+50+(SCREEN_WIDTH-22)/394.0*160;
        height-=33;
    }else if (model.ThumbStyle==3){
        height =[TGTools getSpaceLabelHeight:model.Title withFont:[UIFont systemFontOfSize:real_size(15)] withWidth:SCREEN_WIDTH-27 andLineSpacing:5]+50+(SCREEN_WIDTH-80)/3.0/105*75;
        height-=33;
    }else if (model.ThumbStyle==4){
        height=(SCREEN_WIDTH-22)/394.0*160+10;
    }
    
    return height;
}

#pragma mark - collectionView代理函数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.dataArr.count;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section==0) {
        return [self.dataArr[section] count]+self.arr3.count;
    }else if (section==1){
        return [self.dataArr[section] count]+self.arr4.count;
    }else if (section==2){
        return [self.dataArr[section] count]+self.arr5.count;
    }else if (section==3){
        return [self.dataArr[section] count]+self.arr6.count;
    }
    return [self.dataArr[section] count];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arr=self.dataArr[indexPath.section];
    if (indexPath.row<arr.count) {
        LabCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"LabCell" forIndexPath:indexPath];
        GalleryContentModel *model=arr[indexPath.row];
        [cell setLeftTitle:[NSString stringWithFormat:@"%@ %@",model.LastIssue,model.Name] andLeft:20];
        return cell;
    }else{
        if (indexPath.section==0) {
            return [self cellWithModel:self.arr3[indexPath.row-arr.count] andIndexPath:indexPath];
        }else if (indexPath.section==1){
            return [self cellWithModel:self.arr4[indexPath.row-arr.count] andIndexPath:indexPath];
        }else if (indexPath.section==2){
            return [self cellWithModel:self.arr5[indexPath.row-arr.count] andIndexPath:indexPath];
        }else{
            return [self cellWithModel:self.arr6[indexPath.row-arr.count] andIndexPath:indexPath];
        }
    }
}

- (UICollectionViewCell *)cellWithModel:(AdvertisingModel *)model andIndexPath:(NSIndexPath *)indexPach{
    if (model.ThumbStyle==0) {
        AdvertisingNoImageCell *cell=[self.collectionView.collectionView dequeueReusableCellWithReuseIdentifier:@"AdvertisingNoImageCell" forIndexPath:indexPach];
        [cell setModel:model];
        return cell;
    }else if (model.ThumbStyle==1){
        AdvertisingSmallImageCell *cell=[self.collectionView.collectionView dequeueReusableCellWithReuseIdentifier:@"AdvertisingSmallImageCell" forIndexPath:indexPach];
        [cell setModel:model];
        return cell;
        
    }else if (model.ThumbStyle==2){
        AdvertisingBigImageCell *cell=[self.collectionView.collectionView dequeueReusableCellWithReuseIdentifier:@"AdvertisingBigImageCell" forIndexPath:indexPach];
        [cell setModel:model];
        return cell;
    }else if (model.ThumbStyle==3){
        AdvertisingMoreImageCell *cell=[self.collectionView.collectionView dequeueReusableCellWithReuseIdentifier:@"AdvertisingMoreImageCell" forIndexPath:indexPach];
        [cell setModel:model];
        return cell;
    }else{
        ImageCell *cell=[self.collectionView.collectionView dequeueReusableCellWithReuseIdentifier:@"ImageCell" forIndexPath:indexPach];
        if (model.ThumbList.count>0) {
            [cell.imageV sd_setImageWithURL:[NSURL URLWithString:model.ThumbList[0]] placeholderImage:[UIImage imageNamed:@"big_loding"]];
        }else{
            cell.imageV.image=[UIImage imageNamed:@"big_loding"];
        }
        return cell;
    }
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

-(NSArray *)sectionIndexTitlesForDSCollectionView:(DSCollectionView *)tableView{
    return sections;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (self.model.ExtraData.count>0&&section==0) {
        CGSize size = CGSizeMake(SCREEN_WIDTH, SCREEN_WIDTH/3.0+44+30);
        return size;
    }
    CGSize size = CGSizeMake(SCREEN_WIDTH, 35);
    return size;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *arr=self.dataArr[indexPath.section];
    if (indexPath.row<arr.count) {
        return CGSizeMake(SCREEN_WIDTH/2,40);
    }else{
        if (indexPath.section==0) {
            return CGSizeMake(SCREEN_WIDTH,[self getViewHeight:self.arr3[indexPath.row-arr.count]]);
        }else if (indexPath.section==1){
            return CGSizeMake(SCREEN_WIDTH,[self getViewHeight:self.arr4[indexPath.row-arr.count]]);
        }else if (indexPath.section==2){
            return CGSizeMake(SCREEN_WIDTH,[self getViewHeight:self.arr5[indexPath.row-arr.count]]);
        }else{
            return CGSizeMake(SCREEN_WIDTH,[self getViewHeight:self.arr6[indexPath.row-arr.count]]);
        }
    }
    return CGSizeMake(SCREEN_WIDTH/2,40);
}

- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader)
    {
        GalleryHeadView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"GalleryHeadView" forIndexPath:indexPath];
        NSString *title = [sections objectAtIndex:indexPath.section];
        if (indexPath.section==0&&self.model.ExtraData.count>0) {
            WS(weakSelf);
            headerView.backgroundColor=DEFAULTBGCOLOR;
            [headerView setDataArr:self.model.ExtraData];
            [headerView setTitle:title andShowPic:YES];
            headerView.searchBlock = ^(NSString *searchKey) {
                [weakSelf setSearchKey:searchKey];
            };
            headerView.cancleBlock = ^{
                [weakSelf setModel:self.model];
            };
        }else{
            [headerView setTitle:title andShowPic:NO];
        }
        headerView.backgroundColor=[UIColor whiteColor];
        return headerView;
        
    }else{
        UICollectionReusableView *view = [[UICollectionReusableView alloc] initWithFrame:CGRectZero];
        return view;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *arr=self.dataArr[indexPath.section];
    if (indexPath.row<arr.count) {
        GalleryContentModel *model=self.dataArr[indexPath.section][indexPath.row];
        GalleryDetailVC *vc=[[GalleryDetailVC alloc]init];
        vc.title=model.Name;
        vc.Id=model.Id;
        UIViewController *selfVC=[TGTools viewController:self];
        vc.saveViewController=selfVC;
        [selfVC.navigationController pushViewController:vc animated:YES];
    }else{
        AdvertisingModel *model;
        if (indexPath.section==0) {
            model=self.arr3[indexPath.row-arr.count];
        }else if (indexPath.section==1){
            model=self.arr4[indexPath.row-arr.count];
        }else if (indexPath.section==2){
            model=self.arr5[indexPath.row-arr.count];
        }else{
            model=self.arr6[indexPath.row-arr.count];
        }
        
        if ([model.Title containsString:@"】"]) {
            
            UIPasteboard *copy = [UIPasteboard generalPasteboard];
            NSRange startRange = [model.Title rangeOfString:@"【"];
            NSRange endRange = [model.Title rangeOfString:@"】"];
            NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
            NSString *result = [model.Title substringWithRange:range];
            
            [copy setString:result];
            
            [SVProgressHUD showSuccessWithStatus:@"复制成功"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString: @"weixin://"]];
            });
            
        }else{
            
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString: model.TransferUrl]];
            
        }
    }
}

#pragma mark -- 懒加载
- (DSCollectionView *)collectionView{
    if (_collectionView==nil) {
        StickyHeaderLayout *flowLayout=[[StickyHeaderLayout alloc] init];
        flowLayout.itemSize=CGSizeMake(SCREEN_WIDTH/2,40);
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing=0;
        flowLayout.headerReferenceSize=CGSizeMake(SCREEN_WIDTH, 35);
        _collectionView = [[DSCollectionView alloc] init];
        _collectionView.delegate = self;
        [_collectionView.collectionView setCollectionViewLayout:flowLayout];
        _collectionView.collectionView.alwaysBounceVertical=YES;
        [_collectionView.collectionView setIndicatorStyle:UIScrollViewIndicatorStyleWhite];
        [_collectionView.collectionView setBackgroundColor:[UIColor whiteColor]];
        _collectionView.collectionView.showsVerticalScrollIndicator=NO;
        [_collectionView.collectionView registerClass:[LabCell class] forCellWithReuseIdentifier:@"LabCell"];
        [_collectionView.collectionView registerClass:[AdvertisingMoreImageCell class] forCellWithReuseIdentifier:@"AdvertisingMoreImageCell"];
        [_collectionView.collectionView registerClass:[AdvertisingNoImageCell class] forCellWithReuseIdentifier:@"AdvertisingNoImageCell"];
        [_collectionView.collectionView registerClass:[AdvertisingBigImageCell class] forCellWithReuseIdentifier:@"AdvertisingBigImageCell"];
        [_collectionView.collectionView registerClass:[AdvertisingSmallImageCell class] forCellWithReuseIdentifier:@"AdvertisingSmallImageCell"];
        [_collectionView.collectionView registerClass:[ImageCell class] forCellWithReuseIdentifier:@"ImageCell"];
        [_collectionView.collectionView registerClass:[GalleryHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"GalleryHeadView"];
    }
    return _collectionView;
}

- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr=[[NSMutableArray alloc]init];
    }
    return _dataArr;
}


@end
